package com.weixiao.controller;

import com.weixiao.entity.User;
import com.weixiao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * author 韩诚
 * date 2022/12/15
 */
@RestController
@RequestMapping("redis")
public class RedisController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 向redis中添加数据
     *
     * @param key
     * @param value
     */
    @GetMapping("add")
    public void add(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }

    /**
     * 向redis中添加数据并设置过期时间
     *
     * @param key
     * @param value
     */
    @GetMapping("addTiming")
    public void addTiming(String key, String value) {
        //向redis中添加数据并设置过期时间，TimeUnit.SECONDS:时间单位（枚举）
        stringRedisTemplate.opsForValue().set(key, value, 10, TimeUnit.SECONDS);
    }

    /**
     * 向redis中添加hash类型数据
     *
     * @param hash
     * @param key
     * @param value
     */
    @GetMapping("addHash")
    public void addHash(String hash, String key, String value) {
        redisTemplate.opsForHash().put(hash, key, value);
        System.out.println(redisTemplate.opsForHash().get(hash, key));
    }

    /**
     * 获取List集合
     *
     * @return
     */
    @RequestMapping("getUserList")
    public List<User> getUserList() {
        return userService.selectUserList(new User());
    }

    /**
     * 获取Map集合
     *
     * @return
     */
    @RequestMapping("getUserMap")
    public Map<Integer, User> getUserMap() {
        return userService.selectUserMap(new User());
    }

    /**
     * 删除redis中数据
     *
     * @param key
     */
    @GetMapping("del")
    public void del(String key) {
        stringRedisTemplate.delete(key);
    }


    /**
     * 修改数据
     */
    @RequestMapping("edit")
    public void edit() {
        User user = new User();
        user.setUserId(1);
        user.setUserName("陈佳宏");
        user.setUserSex("女");
        user.setUserAge(22);
        userService.edit(user);
    }
}
